<template>
  <div class="mainor">
    <div class="main_spac1" style="padding-bottom: 5px">
      <el-form
        :inline="true"
        :rules="rules"
        :model="monitorForm"
        class="demo-form-inline marginTop0"
        ref="userListFrom"
        label-width="100px"
      >
        <div class="main_spac1 padding0" style="padding-bottom: 5px">
          <div class="main_white padding10">
            <div class="main_crumbs boxdq">
              <div class="main_crumbs_l">
                <a href="javascript:;" @click="$router.back(-1)">
                  <i class="el-icon-arrow-down"></i>返回
                </a>
                <em>|</em>
                <span>编辑采购单</span>
              </div>
            </div>
            <div class="marginTop15">
              <el-form-item label="采购方式" prop="form.mode">
                <el-select
                  v-model.trim="monitorForm.form.mode"
                  placeholder="采购方式"
                  :disabled="true"
                  class="wid220"
                  @change="
                    (monitorForm.form.buyer_id = null),
                      (monitorForm.form.supplier_id = null)
                  "
                >
                  <el-option
                    v-for="(mode, index) in info.mode"
                    :key="index"
                    :label="mode"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label=""
                prop="form.buyer_id"
                v-if="monitorForm.form.mode == 1"
                :rules="rules.buyer_id"
              >
                <el-select
                  v-model.trim="monitorForm.form.buyer_id"
                  ref="company"
                  placeholder="采购员"
                  :disabled="true"
                  class="wid220"
                >
                  <el-option
                    v-for="(buyer, index) in info.buyer"
                    :key="index"
                    :label="buyer"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label=""
                prop="form.supplier_id"
                v-if="monitorForm.form.mode > 1"
                ref="company"
                :rules="rules.supplier_id"
              >
                <el-select
                  v-model.trim="monitorForm.form.supplier_id"
                  placeholder="供应商"
                  :disabled="true"
                  class="wid220"
                >
                  <el-option
                    v-for="(supplier, index) in info.supplier"
                    :key="index"
                    :label="supplier"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="采购日期"
                prop="form.purchase_time"
                :rules="rules.createTime"
              >
                <el-date-picker
                  v-model="monitorForm.form.purchase_time"
                  type="date"
                  class="time220"
                  :disabled="true"
                  :editable="false"
                  placeholder="采购日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                />
              </el-form-item>
              <div class="clearfix"></div>
              <div class="marginTop5">
                <el-form-item
                  label="备注："
                  prop="form.remark"
                  class="marginRight0 marginTop10 remark_in"
                >
                  <el-input
                    v-model.trim="monitorForm.form.remark"
                    placeholder="备注"
                    clearable
                    @change="isEdit = true"
                  ></el-input>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <div class="main_white padding10 marginTop10 marginBottom10">
          <div>
            <div class="main_white">
              <div class="mainor_sp boxha">
                <ul class="box">
                  <li class="box">
                    <span> <em>*</em>商品名称： </span>
                    <el-autocomplete
                      v-model="formsp.value"
                      :trigger-on-focus="true"
                      ref="searchSelect"
                      @clear="$refs.searchSelect.$children[0].blur()"
                      class="wid240 main_comm"
                      :fetch-suggestions="
                        (queryString, cb) => {
                          querySearchAsync(queryString, cb);
                        }
                      "
                      placeholder="请输入内容"
                      clearable
                      :highlight-first-item="true"
                      value-key="name"
                      @select="
                        (item) => {
                          handleSelect(item);
                        }
                      "
                    >
                      <template slot-scope="{ item }">
                        <div class="main_name">
                          <span>
                            {{ item.goods.name }}【{{
                              item.spu_name ? item.spu_name.title : ""
                            }}】
                          </span>
                          <span class="code">{{ item.goods_spu_code }}</span>
                        </div>
                      </template>
                    </el-autocomplete>
                  </li>
                  <li class="box">
                    <span> <em>*</em>数量： </span>
                    <el-input
                      v-model.trim="formsp.num"
                      ref="focusw2"
                      placeholder="数量"
                      clearable
                      class="wid140"
                      @keyup.enter.native="mainor_sp"
                    ></el-input>
                  </li>
                </ul>
                <div class="marginBottom10">
                  <el-button type="primary" @click="mainor_qr"
                    >确认(回车)</el-button
                  >
                  <el-button
                    class="reset marginLeft5"
                    type="info"
                    @click="reset"
                    >重置</el-button
                  >
                </div>
              </div>
              <div class="main_table marginTop0" style="min-height: 370px">
                <el-table
                  ref="multipleTable"
                  :data="monitorForm.list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                  :header-cell-class-name="this.$verticaline"
                >
                  <el-table-column label="序号" width="80">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column
                    label="名称"
                    prop="name"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope"
                      >{{ scope.row.name }}【{{
                        scope.row.spu_name
                      }}】</template
                    >
                  </el-table-column>
                  <el-table-column label="单位" prop="unit" />
                  <el-table-column
                    label="近一次采购价"
                    prop="purchase_price"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    label="数量"
                    prop="price"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'list.' + scope.$index + '.purchase_num'"
                        :rules="rules.purchase_num"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.purchase_num"
                          :ref="'purchase_num' + scope.row.goods_spu_id"
                          placeholder="数量"
                          class="wid110"
                          @change="isEdit = true"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="备注"
                    prop="remark"
                    width="350"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-input
                          v-model.trim="scope.row.remark"
                          placeholder="备注"
                          class="wid240"
                        ></el-input>
                      </el-form-item>
                      <el-link
                        type="danger"
                        @click="
                          scope.row.show
                            ? lengt <= 1
                              ? endDelete()
                              : scdelete(scope.$index, true)
                            : scdelete(scope.$index)
                        "
                        class="paddingTop20"
                        >删除</el-link
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="newConBox_p200 paddingBottom10" id="newConBox">
                <div class="newConBox_h32">
                  <div
                    :class="[
                      'mainor_pr boxdq newConBox ',
                      { on: searchBarFixed },
                    ]"
                  >
                    <div class="mainor_prl">
                      <el-button
                        type="primary"
                        @click="preservation"
                        v-repeatClick
                        >保存</el-button
                      >
                      <el-button @click="$router.back(-1)">取消</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
const shuju = {
  list: {
    name: "",
    goods_id: "",
    goods_spu_id: "",
    spu_name: "",
    unit: "",
    purchase_price: "",
    purchase_num: "",
    remark: "",
    show: false,
  },
  form: {
    mode: 1,
    purchase_time: "",
    buyer_id: null,
    supplier_id: null,
    remark: "",
  },
  formsp: {
    name: [],
    girard: null,
    num: "",
    value: "",
  },
};

import {
  purchase_base,
  purchase_edit,
  purchaseList_delete,
  purchase_info,
  purchase_checkPurchase,
} from "@/api/purchasing/purchasingPurchase";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/purchasing/purchasingPurchase_add";
import { goods_getGoodsSpu } from "@/api/currency";
import { parseTime } from "@/utils/index";

export default {
  computed: {
    lengt() {
      let zj = 0;
      this.monitorForm.list.map((e) => {
        if (e.show) {
          zj++;
        }
      });
      return zj;
    },
  },
  components: {},
  data() {
    return {
      // 时间
      parseTime,
      // 验证
      rules,
      // 列表数据
      monitorForm: {
        form: {
          mode: 1,
          purchase_time: "",
          buyer_id: null,
          supplier_id: null,
          remark: "",
        },
        list: [],
      },
      deleteIds: [],
      info: [],
      order_price: "",
      // 商品搜索
      formsp: {
        name: [],
        girard: null,
        num: "",
        value: "",
      },
      show: true,
      // id
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
      // 判断是否编辑信息
      isEdit: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },

  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  created() {
    // 信息
    this.purchase_base();
    this.purchase_info();
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (
        this.monitorForm.form.buyer_id == null &&
        this.monitorForm.form.supplier_id == null
      ) {
        this.$message.error("请选择采购员或者供应商");
        this.$refs.company.focus();
        cb([]);
        return;
      }
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          res.data.goods.map((e) => {
            e.name = e.goods.name + "【" + e.spu_unit.title + "】";
          });
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.formsp.name = item;
      this.formsp.girard = item.id;
      this.purchase_checkPurchase();
    },
    purchase_checkPurchase() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                buyer_id: this.monitorForm.form.buyer_id,
                goods_id: formsp.name.goods_id,
                supplier_id: this.monitorForm.form.supplier_id,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          buyer_id: this.monitorForm.form.buyer_id,
          goods_id: formsp.name.goods_id,
          supplier_id: this.monitorForm.form.supplier_id,
        }
      );
      purchase_checkPurchase(data).then((res) => {
        if (res.errcode == 0) {
          this.order_price = res.data.price;
          setTimeout(() => {
            this.$refs.focusw2.focus();
          }, 100);
        } else {
          this.reset();
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      this.isEdit = true;
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.name.name) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let monitorForm_list = JSON.parse(
          JSON.stringify(this.monitorForm.list)
        );
        let ind = 0;
        if (monitorForm_list.length != 0) {
          monitorForm_list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.handle(formsp);
          } else {
            setTimeout(() => {
              this.$refs["purchase_num" + ind].focus();
              this.reset();
              ind = 0;
            }, 100);
          }
        } else {
          this.handle(formsp);
        }
      }
    },
    handle(formsp) {
      let list = JSON.parse(JSON.stringify(shuju.list));
      list.name = formsp.name.goods.name;
      list.goods_id = formsp.name.goods_id;
      list.goods_spu_id = formsp.name.id;
      list.spu_name = formsp.name.spu_name.title;
      list.unit = formsp.name.spu_unit.title;
      list.purchase_price = formsp.name.purchase_price;
      list.purchase_num = formsp.num;
      list.remark = formsp.name.remark;
      this.monitorForm.list.push(list);
      this.reset();
      setTimeout(() => {
        this.$refs.searchSelect.focus();
      }, 100);
    },
    reset() {
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    // 删除
    scdelete(index, type) {
      this.isEdit = true;
      if (type) {
        this.deleteIds.push(this.monitorForm.list[index].id);
        this.monitorForm.list.splice(index, 1);
        // let data = Object.assign(
        //   {
        //     sign: Md5(
        //       objKeySort(
        //         Object.assign(apiUrl().name, {
        //           id: this.monitorForm.list[index].id,
        //         })
        //       ) + apiUrl().appsecret
        //     ),
        //   },
        //   apiUrl().name,
        //   { id: this.monitorForm.list[index].id }
        // );
        // purchaseList_delete(data).then((res) => {
        //   if (res.errcode == 0) {
        //     this.monitorForm.list.splice(index, 1);
        //   } else {
        //     this.$message.error(res.errmsg);
        //   }
        // });
      } else {
        this.monitorForm.list.splice(index, 1);
      }
    },
    endDelete() {
      this.$message.error("采购单最后一个商品无法删除");
    },
    // 保存
    preservation(type) {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (this.monitorForm.list.length == 0) {
            this.$message.error("请至少添加一个商品");
            return;
          }
          let form = JSON.parse(JSON.stringify(this.monitorForm.form));
          form.buyer_id = form.buyer_id ? form.buyer_id : 0;
          form.supplier_id = form.supplier_id ? form.supplier_id : 0;
          let sz = JSON.parse(JSON.stringify(this.monitorForm.list));
          let list = sz.map((e) => {
            let { show, ...sz } = e;
            return { ...sz };
          });
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            form,
            { delete_ids: this.deleteIds.join(",") },
            { list: JSON.stringify(list), id: this.id }
          );

          purchase_edit(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.isEdit = false;
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    // 信息
    purchase_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      purchase_base(data).then((res) => {
        if (res.errcode == 0) {
          this.info = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 基本信息
    purchase_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      purchase_info(data).then((res) => {
        if (res.errcode == 0) {
          this.standard(res.data);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    standard(data) {
      let arry = [];
      (this.monitorForm.form.mode = data.info.mode),
        (this.monitorForm.form.purchase_time = parseTime(
          data.info.purchase_time,
          "{y}-{m}-{d}"
        )),
        (this.monitorForm.form.buyer_id =
          data.info.buyer_id == 0 ? null : data.info.buyer_id),
        (this.monitorForm.form.supplier_id =
          data.info.supplier_id == 0 ? null : data.info.supplier_id),
        (this.monitorForm.form.remark = data.info.remark);
      data.info.purchase_list.map((e) => {
        arry.push({
          id: e.id,
          name: e.name,
          goods_id: e.goods_id,
          goods_spu_id: e.goods_spu_id,
          spu_name: e.spu_name,
          unit: e.unit,
          purchase_price: e.purchase_price,
          purchase_num: e.purchase_num,
          remark: e.remark,
          show: true,
        });
      });
      this.monitorForm.list = arry;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.mainor {
  /deep/.el-button--default {
    border-color: $menuActiveText;
    color: $menuActiveText;
  }
  /deep/.el-form {
    margin-top: 10px;
    /deep/.el-form-item--mini.el-form-item,
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }
  }
  .remark_in {
    width: 100%;
    /deep/.el-form-item__content {
      width: 80%;
      .el-input {
        width: 57.9%;
      }
    }
  }
  .newConBox.on {
    width: calc(100% - 230px);
    padding-left: 0;
  }
  .main_crumbs_us {
    width: 240px;
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
    /deep/.el-button--default {
      border-color: $subActive;
      color: $menuText;
      &:hover {
        border-color: $menuActiveText;
        color: $menuActiveText;
      }
    }
    .mainor_prr {
      font-size: $font_16;
      color: $colour_18;
      span {
        color: #fe3b3b;
        margin-left: 10px;
      }
    }
  }
}
.main_name {
  display: flex;
  flex-direction: column;
  line-height: initial;
  padding: 8px 0;
  .code {
    color: #999;
  }
}
</style>
